import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

/**
 * 客户端网络编程
 */
public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIp;//IP
    private int serverPort;//端口号
    public UdpEchoClient(String ip, int port) throws SocketException {
        serverIp = ip;
        serverPort = port;
        // 这个 new 操作, 就不再指定端⼝了. 让系统⾃动分配⼀个空闲端⼝.
        socket = new DatagramSocket();
    }
    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("客⼾端启动!");
        while (true) {
            // 1. 从控制台读取⽤⼾输⼊的内容
            System.out.print("-> "); // 命令提⽰符, 提⽰⽤⼾要输⼊字符串.
            String request = scanner.next();
            // 2. 构造请求对象, 并发给服务器.
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),InetAddress.getByName(serverIp), serverPort);
            socket.send(requestPacket);
            // 3. 读取服务器的响应, 并解析出响应内容.
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4,socket.receive(requestPacket);
            String response = new String(responsePacket.getData(), 0, responsePacket);
            // 4. 显⽰到屏幕上.
            System.out.println(response);
        }
    }
    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1", 9090);
        client.start();
    }
}